//
//  MSLoginDataSource.m
//  MSJD
//
//  Created by 箭军刘 on 2018/10/17.
//  Copyright © 2018年 xiangbo. All rights reserved.
//

#import "MSLoginDataSource.h"

#import <YYKit/NSString+YYAdd.h>

@implementation MSLoginDataSource

+ (void)loginWithPhone:(NSString *)phone
                   pwd:(NSString *)pwd
               success:(void (^)(NSDictionary *responseInfo))success
               failure:(void (^)(NSError *error))failure {
    
    NSString *requestUrl = @"v1/user/login";
    NSDictionary *param = @{@"phone":[MSSafeObject stringInfo:phone],
                            @"pass":[[MSSafeObject stringInfo:pwd] md5String]};
    
    [MSNetworkAPI POST:requestUrl domain:API_TOPHRMING parameters:param isJsonData:NO success:^(id responseObject) {
        if ([responseObject isKindOfClass:[NSNull class]]) {
            if (failure) {
                failure(nil);
            }
            return ;
        }
        if (success) {
            success((NSDictionary *)responseObject);
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)queryWechatAccountInfoAndOpenIdWithCode:(NSString *)code
                                        success:(void (^)(NSDictionary *responseInfo))success
                                        failure:(void (^)(NSError *error))failure {
    NSString *requestUrl = @"https://api.weixin.qq.com/sns/oauth2/access_token";
    NSDictionary *param = @{@"appid":@"wxf438698c2a1b15f9", @"secret":@"4fa7f6bec078443f562cb931e12bf974", @"code":[MSSafeObject stringInfo:code], @"grant_type":@"authorization_code"};
    [MSNetworkAPI GET:requestUrl domain:@"" parameters:param success:^(id responseObject) {
        // EXAMPLE
        /*
         {
         "access_token" = "14_gXfDVbAkNXJ3tQtZ8LLlk_rVNedrHGcffjqCDOjiiR5_ZGUFJlfxaejSb-Wjc_kR5UWvhLA-036Kx-vVKyTcFPPkx_yq4Jh-0gl6UBWlHXE";
         "expires_in" = 7200;
         openid = "o5ATU1MyIXz9dRMkYP-CdOO1cEdM";
         "refresh_token" = "14_6Ga9HAS4vX7VsSegkWM999lN1ms8S3u6sHmBAt_kl7QHuXYEkbI84F-NezfDfUAeodx9amODEEsJTK3HoQUqYnU7ARi7bM3z4fChJn_OT2k";
         scope = "snsapi_userinfo";
         unionid = "owCDvtxU4boqUa_xxbvOKtRWLNYQ";
         }
         */
        if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) {
            NSError *customError = [NSError errorWithDomain:API_TOPHRMING code:-999 userInfo:@{NSLocalizedDescriptionKey:@"账号信息异常，登录失败"}];
            if (failure) {
                failure(customError);
            }
            return ;
        }
        // 请求账号信息
        NSString *infoRequestUrl = @"https://api.weixin.qq.com/sns/userinfo";
        NSDictionary *responseInfo = (NSDictionary *)responseObject;
        NSString *accessToken = [MSSafeObject stringInfo:responseInfo[@"access_token"]];
        NSString *openId = [MSSafeObject stringInfo:responseObject[@"openid"]];
        NSDictionary *param = @{@"access_token":accessToken, @"openid":openId};
        [MSNetworkAPI GET:infoRequestUrl domain:@"" parameters:param success:^(id responseObject) {
            if (success) {
                success((NSDictionary *)responseObject);
            }
        } failure:^(NSError *error) {
            if (failure) {
                failure(error);
            }
        }];
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}


+ (void)wechatLoginWithPhone:(NSString *)phone
                      avatar:(NSString *)avatar
                      gender:(NSInteger)gender
                      openId:(NSString *)openId
                    nickname:(NSString *)nickname
                     success:(void (^)(NSDictionary *responseInfo))success
                     failure:(void (^)(NSError *error))failure {
    
    NSString *requestUrl = @"v1/wechat/login";
    NSDictionary *param = @{@"phone":[MSSafeObject stringInfo:phone],
                            @"avatar":[MSSafeObject stringInfo:avatar],
                            @"gender":@(gender),
                            @"openId":[MSSafeObject stringInfo:openId],
                            @"nickname":[MSSafeObject stringInfo:nickname]};
    [MSNetworkAPI POST:requestUrl domain:API_TOPHRMING parameters:param isJsonData:NO success:^(id responseObject) {
        if (success) {
            success((NSDictionary *)responseObject);
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)sendSMSCodeWithPhone:(NSString *)phone
                      source:(NSInteger)source
                     success:(void (^)(NSDictionary *responseInfo))success
                     failure:(void (^)(NSError *error))failure {
    
    NSString *requestUrl = @"";
    NSDictionary *param = nil;
    NSString *secretKey = @"QhY2Ux5i";
//    NSString *timeStamp = [DeviceInfo getCurrentTimestamp];
    NSString *sign = [[NSString stringWithFormat:@"%@%@", phone, secretKey] md5String];
    if (source == 0) {
        // 注册
        requestUrl = @"v1/sms/register";
        param = @{@"phone":[MSSafeObject stringInfo:phone], @"sign":sign};
    } else if (source == 1) {
        // 重设
        requestUrl = @"v1/sms/reset";
        param = @{@"phone":[MSSafeObject stringInfo:phone], @"sign":sign};
    } else if (source == 2) {
        // 绑定手机
        requestUrl = @"v1/sms/bind";
        NSInteger uid = [[UserAccesser loadAccount].userId integerValue];
        param = @{@"phone":[MSSafeObject stringInfo:phone], @"sign":sign, @"uid":@(uid)};
    }

    [MSNetworkAPI POST:requestUrl domain:API_TOPHRMING parameters:param isJsonData:NO success:^(id responseObject) {
        if (success) {
            success((NSDictionary *)responseObject);
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)resetPasswordWithType:(NSInteger)urlType
                        Phone:(NSString *)phone
                     password:(NSString *)password
                         code:(NSString *)code
                      codeDic:(NSDictionary *)codeDic
                      success:(void (^)(NSDictionary *responseInfo))success
                      failure:(void (^)(NSError *error))failure {
    NSString *requestUrl = (urlType == 1)?@"v1/user/resetpass":@"v1/user/register";
    NSString *time = [MSSafeObject stringInfo:codeDic[@"time"]];
    NSString *hash = [MSSafeObject stringInfo:codeDic[@"hash"]];
    NSDictionary *param = @{@"phone":[MSSafeObject stringInfo:phone],
                            @"time":time,
                            @"hash":hash,
                            @"code":@([code integerValue]),
                            @"pass":[[MSSafeObject stringInfo:password] md5String]};
    [MSNetworkAPI POST:requestUrl domain:API_TOPHRMING parameters:param isJsonData:NO success:^(id responseObject) {
        if (success) {
            success((NSDictionary *)responseObject);
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)bindPhoneWithPhone:(NSString *)phone
                      code:(NSString *)code
                   codeDic:(NSDictionary *)codeDic
                   success:(void (^)(NSDictionary *responseInfo))success
                   failure:(void (^)(NSError *error))failure{
    NSString *requestUrl = @"v1/user/bind";
    NSString *time = [MSSafeObject stringInfo:codeDic[@"time"]];
    NSString *hash = [MSSafeObject stringInfo:codeDic[@"hash"]];
    NSInteger uid = [[UserAccesser loadAccount].userId integerValue];
    NSDictionary *param = @{@"phone":[MSSafeObject stringInfo:phone],
                            @"code":[MSSafeObject stringInfo:code],
                            @"time":time,
                            @"hash":hash,
                            @"uid":@(uid)};
    [MSNetworkAPI POST:requestUrl domain:API_TOPHRMING parameters:param isJsonData:NO success:^(id responseObject) {
        if (success) {
            success((NSDictionary *)responseObject);
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)queryAppReviewStatus:(void (^)(NSDictionary *responseInfo))success
                     failure:(void (^)(NSError *error))failure {
    NSString *requestUrl = @"v1/version/status";
    NSDictionary *param = @{@"version":[MSSafeObject stringInfo:[DeviceInfo getBigVersion]]};
    [MSRequestClient GET:requestUrl parameters:param responseClassType:NSDictionary.class success:^(id responseObject) {
        if (success) {
            success((NSDictionary *)responseObject);
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

@end
